import domToImage from "dom-to-image"
import {saveAs} from 'file-saver';
import {MutableRefObject, useRef} from "react";

export const useDomToImageRef = (): [MutableRefObject<any>, (filename?: string) => void] => {
    const ref = useRef(null);

    const downloadImage = (filename?: string) => {
        if (ref.current) {
            domToImage.toPng(ref.current).then((image: string) => {
                fetch(image).then(res => res.blob()).then((blob) => {
                    saveAs(blob, filename ?? 'my-component.png');
                })
            })
        }
    }

    return [ref, downloadImage];
};
